import HeaderView from "@/component/Header"
import TimeOut from "@/component/TimeOut"
import TabbarView from "@/component/Tabbar"
import { useEffect, useState } from "react"
import { GetUser, UserLogout } from "@/api/mine"
import style from './index.module.scss'
import { Image, List, Button, Toast } from "antd-mobile"
import { useNavigate } from "react-router-dom"
import { removeCookie } from "@/utils"

const Mine = () => {
  const navigate = useNavigate()  
  const [flag, setFlag] = useState(false) // 错误提示    
  const [user, setUser] = useState({img: '', name: '', email: ''}) 
  
  // 数据初始化
  const init = async () => {
    const res = await GetUser().catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') setFlag(true)
    })

    try {
      if(res?.status === 200) {
        setUser({img: res.data.avatar_url, name: res.data.name, email: res.data.email})
      }  
    } catch (error) {
      console.log(error)  
    }
  }

  useEffect(() => { init() }, [])

  // 用户退出
  const logout = async () => {
    const res = await UserLogout().catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
        Toast.show({icon: 'fail', content: '请稍后再试', maskClickable: false, duration: 1500})
      }
    })

    try {
      if(res?.status === 204) {
        Toast.show({icon: 'success', content: '退出成功', maskClickable: false, afterClose: () => {
          navigate('/home')
          removeCookie('token')  
          removeCookie('id')  
          removeCookie('productNum')  
        }})
      }  
    } catch (error) {
      console.log(error)  
    }
  }

  return (
    <>
      {/* 头部信息 */}
      <HeaderView title="个人中心" backIcon={false}/>
 
      {/* 用户信息  */}
      {
        user.name 
        &&
        <div className={style.mineBox}>
          <div className={style.boxHeader}>
           <div className={style.boxHeaderLeft}><Image src={user.img}/></div>
           <div className={style.boxHeaderRight}>
              <p>昵称: {user.name}</p>
              <p>账号: {user.email}</p>
              <p>个性签名: 希望我有钱, 让爸妈过的好</p>
           </div>
          </div>
        
          <List className={style.mineList}>
           <List.Item arrowIcon onClick={() => navigate('/collect')}>我的收藏</List.Item>
           <List.Item arrowIcon>我的订单</List.Item>
           <List.Item arrowIcon>账号管理</List.Item>
           <List.Item arrowIcon onClick={() => navigate('/address')}>地址管理</List.Item>
           <List.Item arrowIcon>关于我们</List.Item>
          </List>  

          <div className={style.btn}>
          <Button color="success" block shape="rounded" style={{"--background-color": '#07c160'}} onClick={() => logout()}>退出</Button>
          </div>

          {/* tabbar信息 */}
          <TabbarView/>
        </div>
      }

      {/* 错误提示页面 */}
      {flag && <TimeOut/>}
    </>
  )
}

export default Mine